import {
  LockOutlined,
  UserOutlined,
  SafetyOutlined
} from '@ant-design/icons';
import { Alert, message } from 'antd';
import React, { useState } from 'react';
import ProForm, { ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, SelectLang, useModel } from 'umi';
import { login } from '@/services/ant-design-pro/api';

import Captcha from 'react-captcha-code';

import styles from './index.less';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');

  const [code1, setcode] = useState("");//验证码
  console.log(initialState);

  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    console.log(values);
    try {
      let { code }: any = values;
      if (code !== code1) {
        message.error("验证码输入错误");
        return false;
      }
      // 登录
      const msg: any = await login({ ...values, type });
      if (msg.status === 'ok') {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);

        //登录成功后，信息存储到本地存储中去
        sessionStorage.setItem("admin_users", JSON.stringify(msg.data));
        sessionStorage.setItem("token", msg.data.token);

        await fetchUserInfo();
        // return false;
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      // setUserLoginState(msg);
      message.error(msg.msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
    }
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <div className={styles.logo}>
          <img src="/login.png" />
        </div>
        <LoginForm
          logo={<img alt="logo" src="/logo1.png" />}
          title="客达天下"
          subTitle={intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
          initialValues={{
            autoLogin: true,
          }}
          grid={true}
          submitter={{
            submitButtonProps: {
              style: {
                // display: "none",
                background: "#05cc95",
                width: "100%",
                borderRadius: "20px",
                border: "none"
              }
            }
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >

          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码1111错误(admin/ant.design)',
              })}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '用户名: admin or user',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '密码: ant.design',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
              <ProForm.Group>
                <ProFormText
                  name="code"
                  fieldProps={{
                    size: "large",
                    prefix: <SafetyOutlined className={styles.prefixIcon} />
                  }}
                  colProps={{ span: 16 }}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.password1.required"
                          defaultMessage="请输入验证码！"
                        />
                      ),
                    },
                  ]}
                  placeholder="输入验证码"
                />
                <div>
                  <Captcha onChange={(code) => { setcode(code); return code; }} />
                </div>
              </ProForm.Group>
            </>
          )}
        </LoginForm>
      </div>
      {/* <Footer /> */}
    </div>
  );
};

export default Login;
